import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:msh_checkbox/msh_checkbox.dart';
import 'package:klcpopup/klcpopup.dart';
import 'package:confetti/confetti.dart';
import 'package:qilo/core/constants/app_colors.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/services/reminder_service.dart';
import '../../../core/providers/practice_schedule_provider.dart';
import '../../../core/models/practice_task_model.dart';

/// 练习计划页面
class PracticeSchedulePage extends StatefulWidget {
  const PracticeSchedulePage({super.key});

  @override
  State<PracticeSchedulePage> createState() => _PracticeSchedulePageState();
}

class _PracticeSchedulePageState extends State<PracticeSchedulePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  TimeOfDay? _selectedReminderTime;
  DateTime? _selectedDate;
  int? _selectedHour;
  int? _selectedMinute;

  late ConfettiController _confettiController;

  @override
  void initState() {
    super.initState();
    _confettiController = ConfettiController(
      duration: const Duration(seconds: 2),
    );
  }

  @override
  void dispose() {
    _confettiController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/plan-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          SingleChildScrollView(
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 顶部标题栏
                  _buildTopSection(),

                  // 任务容器
                  _buildTaskContainer(),

                  // 设置按钮
                  _buildSettingsButton(),

                  // 底部间距
                  SizedBox(height: 140.h),
                ],
              ),
            ),
          ),
          // Confetti Widget
          Align(
            alignment: Alignment.topCenter,
            child: ConfettiWidget(
              confettiController: _confettiController,
              blastDirection: 1.5708,
              particleDrag: 0.05,
              emissionFrequency: 0.05,
              numberOfParticles: 3,
              gravity: 0.05,
              shouldLoop: false,
              colors: const [
                Colors.green,
                Colors.blue,
                Colors.pink,
                Colors.orange,
                Colors.purple,
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建顶部区域
  Widget _buildTopSection() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 20.h, bottom: 0.h),
      height: 99.w,
      child: Stack(
        children: [
          Positioned(
            left: 0,
            top: 0,
            bottom: 0,
            right: 110.w,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Daily Practice Plan',
                style: TextStyle(
                  color: Color(0xFF5A4000),
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  fontFamily: 'Porter Sans Block',
                  shadows: [
                    Shadow(
                      offset: const Offset(2, 2),
                      blurRadius: 4,
                      color: Colors.black.withValues(alpha: 0.5),
                    ),
                  ],
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          // 右侧图片
          Positioned(
            right: 0,
            top: 0,
            child: Container(
              width: 99.w,
              height: 99.w,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/community-top.png'),
                  fit: BoxFit.contain,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建任务容器
  Widget _buildTaskContainer() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: AspectRatio(
        aspectRatio: 349 / 466,
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/task-bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(
              children: [
                SizedBox(height: 10.h),
                // 任务标题图片
                Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: Container(
                    width: 131.w,
                    height: 28.h,
                    decoration: const BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/task-title.png'),
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 10.h),
                Expanded(
                  child: Consumer<PracticeScheduleProvider>(
                    builder: (context, provider, child) {
                      if (provider.isLoading) {
                        return const Center(child: CircularProgressIndicator());
                      }

                      return ListView.builder(
                        padding: EdgeInsets.zero,
                        itemCount: provider.practiceItems.length,
                        itemBuilder: (context, index) {
                          return _buildTaskItem(
                            index,
                            provider.practiceItems[index],
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建单个任务项
  Widget _buildTaskItem(int index, PracticeTaskModel task) {
    final isEmpty = task.title.isEmpty;

    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 6.h),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border(bottom: BorderSide(color: AppColors.border, width: 1)),
      ),
      child: Row(
        children: [
          // 完成状态复选框
          MSHCheckbox(
            size: 20.w,
            value: task.isCompleted,
            colorConfig: MSHColorConfig.fromCheckedUncheckedDisabled(
              checkedColor: AppColors.iconColor,
              uncheckedColor: Color(0xFF333333),
              disabledColor: Colors.grey.withValues(alpha: 0.3),
            ),
            style: MSHCheckboxStyle.fillScaleColor,
            onChanged: (selected) {
              if (!isEmpty) {
                _toggleTaskCompletion(index);
              }
            },
          ),
          SizedBox(width: 12.w),
          // 任务文本
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (isEmpty) {
                  _showAddTaskDialog(index);
                } else {
                  _showTaskDetailDialog(task.title);
                }
              },
              child: Text(
                isEmpty ? 'Fill in Your Plan for Today' : task.title,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: isEmpty ? Colors.grey : Colors.black87,
                  decoration:
                      task.isCompleted ? TextDecoration.lineThrough : null,
                  fontWeight: FontWeight.w600,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建设置按钮
  Widget _buildSettingsButton() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 0.h),
      child: GestureDetector(
        onTap: _showReminderTimeSelector,
        child: SizedBox(
          width: double.infinity,
          child: AspectRatio(
            aspectRatio: 346 / 79,
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/setting.png'),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 显示添加任务对话框
  void _showAddTaskDialog(int index) {
    final TextEditingController controller = TextEditingController();
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.dimmed,
      child: Material(
        color: Colors.transparent,
        child: _buildAddTaskPopup(controller, index, popupController),
      ),
    );
  }

  /// 构建添加任务弹窗内容
  Widget _buildAddTaskPopup(
    TextEditingController controller,
    int index,
    KLCPopupController popupController,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 40.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.2),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题区域
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: AppColors.iconColor,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(16.r),
                topRight: Radius.circular(16.r),
              ),
            ),
            child: Text(
              'Add Practice Plan',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                fontFamily: 'Porter Sans Block',
              ),
              textAlign: TextAlign.center,
            ),
          ),

          Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  'Enter your practice plan for today:',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[700],
                    fontWeight: FontWeight.w500,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 16.h),

                // 输入框
                Container(
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: Colors.grey[300]!, width: 1),
                  ),
                  child: TextField(
                    controller: controller,
                    autofocus: true,
                    maxLines: 2,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
                      hintText: 'Enter task description...',
                      hintStyle: TextStyle(
                        color: Colors.grey[500],
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(16.w),
                    ),
                    style: TextStyle(fontSize: 14.sp, color: Colors.black87),
                    onSubmitted: (text) {
                      if (text.trim().isNotEmpty) {
                        context.read<PracticeScheduleProvider>().updateTask(
                          index,
                          text.trim(),
                        );
                        popupController.dismiss();
                      }
                    },
                  ),
                ),

                SizedBox(height: 24.h),

                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () => popupController.dismiss(),
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(22.r),
                            border: Border.all(
                              color: Colors.grey[300]!,
                              width: 1,
                            ),
                          ),
                          child: Center(
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.grey[600],
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 12.w),

                    // 添加按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          final text = controller.text.trim();
                          if (text.isNotEmpty) {
                            context.read<PracticeScheduleProvider>().updateTask(
                              index,
                              text,
                            );
                            popupController.dismiss();
                          }
                        },
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: AppColors.iconColor,
                            borderRadius: BorderRadius.circular(22.r),
                            boxShadow: [
                              BoxShadow(
                                color: AppColors.iconColor.withValues(
                                  alpha: 0.3,
                                ),
                                blurRadius: 8,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                          child: Center(
                            child: Text(
                              'Add Task',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 切换任务完成状态
  void _toggleTaskCompletion(int index) {
    final provider = context.read<PracticeScheduleProvider>();
    final wasCompleted = provider.practiceItems[index].isCompleted;

    provider.toggleTaskCompletion(index);

    // 如果任务从未完成变为完成，触发 confetti 动画
    if (!wasCompleted && provider.practiceItems[index].isCompleted) {
      _confettiController.play();

      // 检查是否所有任务都完成了
      if (provider.isAllTasksCompleted) {
        _showAllTasksCompletedCelebration();
      }
    }
  }

  /// 显示任务详情对话框
  void _showTaskDetailDialog(String taskTitle) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.dimmed,
      child: Material(
        color: Colors.transparent,
        child: _buildTaskDetailPopup(taskTitle, popupController),
      ),
    );
  }

  /// 构建任务详情弹窗内容
  Widget _buildTaskDetailPopup(
    String taskTitle,
    KLCPopupController popupController,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 40.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.2),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题区域
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: AppColors.iconColor,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(16.r),
                topRight: Radius.circular(16.r),
              ),
            ),
            child: Text(
              'Practice Plan Detail',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                fontFamily: 'Porter Sans Block',
              ),
              textAlign: TextAlign.center,
            ),
          ),

          // 内容区域
          Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 任务内容
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: Colors.grey[300]!, width: 1),
                  ),
                  child: Text(
                    taskTitle,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.black87,
                      height: 1.5,
                    ),
                  ),
                ),

                SizedBox(height: 20.h),

                // 关闭按钮
                GestureDetector(
                  onTap: () => popupController.dismiss(),
                  child: Container(
                    width: double.infinity,
                    height: 44.h,
                    decoration: BoxDecoration(
                      color: AppColors.iconColor,
                      borderRadius: BorderRadius.circular(22.r),
                      boxShadow: [
                        BoxShadow(
                          color: AppColors.iconColor.withValues(alpha: 0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Text(
                        'Got it',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 显示提醒时间选择器
  void _showReminderTimeSelector() {
    // 初始化默认选择值
    final now = DateTime.now();
    _selectedDate ??= now;
    _selectedHour ??= 14; // 默认下午2点
    _selectedMinute ??= 0; // 默认0分

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => _buildTimePickerBottomSheet(),
    );
  }

  /// 构建时间选择底部弹出框
  Widget _buildTimePickerBottomSheet() {
    return Container(
      height: 400.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: EdgeInsets.all(20.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Set Reminder Time',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Icon(Icons.close, size: 24.sp),
                ),
              ],
            ),
          ),
          // 时间选择器
          Expanded(child: _buildTimePickerList()),
          // 按钮区域
          Container(
            padding: EdgeInsets.all(20.w),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => Navigator.pop(context),
                    child: Container(
                      height: 50.h,
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(25.r),
                      ),
                      child: Center(
                        child: Text(
                          'Cancel',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (_selectedHour != null && _selectedMinute != null) {
                        final reminderTime = TimeOfDay(
                          hour: _selectedHour!,
                          minute: _selectedMinute!,
                        );

                        // 验证选择的时间不能是过去的时间
                        if (_isTimeInPast(reminderTime)) {
                          AppUtils.showError(
                            context,
                            'Please select a future time for your reminder',
                            title: 'Invalid Time',
                          );
                          return;
                        }

                        context
                            .read<PracticeScheduleProvider>()
                            .setReminderTime(reminderTime);
                        setState(() {
                          _selectedReminderTime = reminderTime;
                        });
                        Navigator.pop(context);
                        _showReminderSetConfirmation();
                      }
                    },
                    child: Container(
                      height: 50.h,
                      decoration: BoxDecoration(
                        color: AppColors.iconColor,
                        borderRadius: BorderRadius.circular(25.r),
                      ),
                      child: Center(
                        child: Text(
                          'Confirm',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.w500,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建时间选择列表
  Widget _buildTimePickerList() {
    return SizedBox(
      height: 300.h,
      child: Row(
        children: [
          // 第一列：日期选择
          Expanded(flex: 2, child: _buildDatePicker()),
          // 第二列：小时选择
          Expanded(flex: 1, child: _buildHourPicker()),
          // 第三列：分钟选择
          Expanded(flex: 1, child: _buildMinutePicker()),
        ],
      ),
    );
  }

  /// 构建日期选择器
  Widget _buildDatePicker() {
    final now = DateTime.now();
    final dates = List.generate(7, (index) => now.add(Duration(days: index)));

    return CupertinoPicker(
      itemExtent: 50.h,
      scrollController: FixedExtentScrollController(
        initialItem: _getSelectedDateIndex(),
      ),
      onSelectedItemChanged: (index) {
        setState(() {
          _selectedDate = dates[index];
        });
      },
      children:
          dates.map((date) {
            return Center(
              child: Text(
                '${_getMonthName(date.month)} ${date.day}th  ${_getWeekdayName(date.weekday)}',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.black87,
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
              ),
            );
          }).toList(),
    );
  }

  /// 构建小时选择器
  Widget _buildHourPicker() {
    return CupertinoPicker(
      itemExtent: 50.h,
      scrollController: FixedExtentScrollController(
        initialItem: _selectedHour ?? 14,
      ),
      onSelectedItemChanged: (index) {
        setState(() {
          _selectedHour = index;
        });
      },
      children: List.generate(24, (index) {
        final isDisabled = _isHourDisabled(index);
        return Center(
          child: Text(
            index.toString().padLeft(2, '0'),
            style: TextStyle(
              fontSize: 14.sp,
              color: isDisabled ? Colors.grey[400] : Colors.black87,
              fontWeight: FontWeight.w600,
            ),
          ),
        );
      }),
    );
  }

  Widget _buildMinutePicker() {
    final minutes = [0, 15, 30, 45];

    return CupertinoPicker(
      itemExtent: 50.h,
      scrollController: FixedExtentScrollController(
        initialItem: _getSelectedMinuteIndex(),
      ),
      onSelectedItemChanged: (index) {
        setState(() {
          _selectedMinute = minutes[index];
        });
      },
      children:
          minutes.map((minute) {
            final isDisabled = _isMinuteDisabled(minute);
            return Center(
              child: Text(
                minute.toString().padLeft(2, '0'),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: isDisabled ? Colors.grey[400] : Colors.black87,
                  fontWeight: FontWeight.w600,
                ),
              ),
            );
          }).toList(),
    );
  }

  int _getSelectedDateIndex() {
    if (_selectedDate != null) {
      final now = DateTime.now();
      final diff = _selectedDate!.difference(now).inDays;
      return diff >= 0 && diff < 7 ? diff : 0;
    }
    return 0;
  }

  int _getSelectedMinuteIndex() {
    final minutes = [0, 15, 30, 45];
    final selectedMinute = _selectedMinute ?? 0;
    return minutes.indexOf(selectedMinute).clamp(0, minutes.length - 1);
  }

  String _getMonthName(int month) {
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    return months[month - 1];
  }

  String _getWeekdayName(int weekday) {
    const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return weekdays[weekday - 1];
  }

  void _showReminderSetConfirmation() {
    if (_selectedReminderTime != null) {
      AppUtils.showSuccess(
        context,
        'We will remind you to practice at ${_selectedReminderTime!.format(context)}',
        title: 'Success',
      );

      ReminderService().scheduleReminder(_selectedReminderTime!);
    }
  }

  /// 检查选择的时间是否是过去的时间
  bool _isTimeInPast(TimeOfDay selectedTime) {
    final now = DateTime.now();
    final selectedDateTime = DateTime(
      _selectedDate?.year ?? now.year,
      _selectedDate?.month ?? now.month,
      _selectedDate?.day ?? now.day,
      selectedTime.hour,
      selectedTime.minute,
    );

    return selectedDateTime.isBefore(now);
  }

  bool _isHourDisabled(int hour) {
    final now = DateTime.now();
    final selectedDate = _selectedDate ?? now;

    if (selectedDate.year == now.year &&
        selectedDate.month == now.month &&
        selectedDate.day == now.day) {
      return hour < now.hour;
    }

    return false;
  }

  bool _isMinuteDisabled(int minute) {
    final now = DateTime.now();
    final selectedDate = _selectedDate ?? now;
    final selectedHour = _selectedHour ?? now.hour;

    if (selectedDate.year == now.year &&
        selectedDate.month == now.month &&
        selectedDate.day == now.day &&
        selectedHour == now.hour) {
      return minute <= now.minute;
    }

    return false;
  }

  void _showAllTasksCompletedCelebration() {
    Future.delayed(const Duration(milliseconds: 500), () {
      if (mounted) {
        AppUtils.showSuccess(
          context,
          'Congratulations! You\'ve completed all your practice tasks for today! 🎉',
          title: '🎸 All Tasks Completed!',
        );
      }
    });
  }
}
